import argparse
import os
import json
from turtle import clear
from download_manager import DownloadManager
import time
from m3u8_downloader import M3U8Downloader, download_batch

mgr = DownloadManager(max_concurrent=1)

class PrintHandler:
    """事件处理器示例：打印下载过程中的各类事件，便于观察与调试。

    实际项目中你可以替换为 GUI/日志记录/状态上报等实现。
    """
    def on_download_start(self, download_id: str, is_live: bool, total_segments: int | None, output_dir: str):
        """整体开始事件：告知是点播还是直播、输出目录与总分片（直播为 None）。"""
        mode = "直播" if is_live else "点播"
        print(f"[event][id={download_id}] 开始下载（{mode}），输出目录: {output_dir}，总分片: {total_segments}")

    def on_overall_progress(self, download_id: str, completed: int, total: int, overall_speed_bps: float):
        """总体进度事件：已完成分片/总数与平均速率（B/s）。"""
        mb_s = overall_speed_bps / (1024 * 1024)
        pct = (completed / total * 100.0) if total else 0.0
        print(f"[event][id={download_id}] 总体进度: {completed}/{total} ({pct:.1f}%)，平均速度: {mb_s:.2f} MB/s")

    def on_segment_start(self, download_id: str, seq: int, filename: str, uri: str):
        """分片开始事件：给出分片序号、文件名与源地址。"""
        print(f"[event][id={download_id}] 分片开始: seq={seq}, file={filename}")

    def on_segment_progress(self, download_id: str, seq: int, filename: str, bytes_downloaded: int, elapsed: float, speed_bps: float):
        """分片进度事件：累计字节、耗时与当前速率（B/s）。"""
        mb_s = speed_bps / (1024 * 1024)
        kb = bytes_downloaded / 1024
        print(f"[event][id={download_id}] 分片进度: seq={seq}, {kb:.0f} KB, {mb_s:.2f} MB/s")

    def on_segment_complete(self, download_id: str, seq: int, filename: str, path: str, elapsed: float, size_bytes: int, speed_bps: float):
        """分片完成事件：分片大小与平均速率。"""
        mb_s = speed_bps / (1024 * 1024)
        sz_mb = size_bytes / (1024 * 1024)
        print(f"[event][id={download_id}] 分片完成: seq={seq}, size={sz_mb:.2f} MB, avg={mb_s:.2f} MB/s")

    def on_segment_error(self, download_id: str, seq: int, filename: str, error: str):
        """分片错误事件：包含异常信息字符串。"""
        print(f"[event][id={download_id}] 分片失败: seq={seq}, file={filename}, err={error}")

    def on_merge_start(self, download_id: str, total_units: float, unit_label: str | None, output_path: str):
        """合并开始事件：给出输出 MP4 路径与单位总数（分片数）。"""
        print(f"[event][id={download_id}] 开始合并为MP4 -> {output_path}")

    def on_merge_progress(self, download_id: str, processed: float, total: float, percent: float):
        """合并进度事件：解析 ffmpeg 输出，估算完成百分比。"""
        print(f"[event][id={download_id}] 合并进度: {percent:.1f}% ({processed:.1f}/{total:.1f})")

    def on_merge_complete(self, download_id: str, output_path: str):
        """合并完成事件：给出最终 MP4 路径。"""
        print(f"[event][id={download_id}] 合并完成: {output_path}")

    def on_download_complete(self, download_id: str, output_dir: str):
        """下载完成事件：任务整体结束，文件在对应的 UUID 子目录中。"""
        print(f"[event][id={download_id}] 下载任务完成，目录: {output_dir}")

    def on_error(self, download_id: str, context: str, message: str):
        """错误事件：从下载器传来解析/网络等错误，不会导致程序崩溃。"""
        print(f"[event][id={download_id}] 错误[{context}]: {message}")

def start_download(param_json: str):
    did = mgr.submit_json(param_json, handler=PrintHandler())
    print(f"[mgr] submitted id={did}")
    return did

def pause_download(did: str):
    mgr.pause(did)
    print(f"[mgr] paused id={did}")
    
def stop_download(did: str, merge_mp4: bool = False):
    ok = mgr.stop(did, merge_mp4=merge_mp4)
    if ok:
        print(f"[mgr] stopped id={did}, merge_mp4={merge_mp4}")
    else:
        print(f"[mgr] failed to stop id={did}")


if __name__ == "__main__":
    # 单任务配置示例：使用 UUID 作为任务 ID。若不指定，管理器会自动生成。
    # 输出目录将使用 `downloads/<UUID>`，确保每个任务的文件相互隔离。
    sample_cfg = {
        "url": "https://manifest.googlevideo.com/api/manifest/hls_playlist/expire/1761901931/ei/CykEaZS5EMqL29gPn6iN-AQ/ip/31.59.133.183/id/3cf435c1e62d5500/itag/96/source/youtube/requiressl/yes/ratebypass/yes/pfa/1/sgoap/clen%3D77650930%3Bdur%3D4797.985%3Bgir%3Dyes%3Bitag%3D140%3Blmt%3D1754674179140701/sgovp/clen%3D312453965%3Bdur%3D4797.926%3Bgir%3Dyes%3Bitag%3D137%3Blmt%3D1754677500086697/rqh/1/hls_chunk_host/rr5---sn-i3b7knzl.googlevideo.com/xpc/EgVo2aDSNQ%3D%3D/met/1761880331,/mh/1J/mm/31,26/mn/sn-i3b7knzl,sn-30a7ynek/ms/au,onr/mv/m/mvi/5/pl/22/rms/au,au/initcwndbps/9081250/bui/AdEuB5RiJVW7gHLfzFb-lKA5vr16IbexXNSOrno8mA7rV1PVjxhAs3w7uamcw0VLqkXrQr5gtFeLPK2f/spc/6b0G_BPkIArkSlh11xZKdmfESkTqeF0ONvaUkTG_MOAgoafgZB19vdGMKtkZ4zS_h_jyqVnUj23DeuG2HM3thzXQ/vprv/1/playlist_type/CLEAN/dover/11/txp/5532534/mt/1761879911/fvip/3/keepalive/yes/fexp/51355912,51552689,51565116,51565681,51580968,51626154/sparams/expire,ei,ip,id,itag,source,requiressl,ratebypass,pfa,sgoap,sgovp,rqh,xpc,bui,spc,vprv,playlist_type/sig/AJfQdSswRQIgL5cqrujDfWQ5lgRA8eLuHbN218ajAJIP1XRZoIBokmYCIQCLtofseCtGVSc6jnieTC8M3Y8QRed1DP61OIr4kN8ZGQ%3D%3D/lsparams/hls_chunk_host,met,mh,mm,mn,ms,mv,mvi,pl,rms,initcwndbps/lsig/APaTxxMwRAIgVBktYkN6FUBPN7gKE2nyuQf-GzF_koD8d_-cec3Xoh8CICW-KYw26Vhr3rILmqCSTe6H_xvhwR2EJ3RAyfuOgSei/playlist/index.m3u8",
        "output_dir": os.path.join(os.getcwd(), "downloads"),
        "workers": 6,
        "timeout": 10,
        "retries": 3,
        "merge_mp4": True,
        "mp4_name": "merged.mp4",
        "cleanup_ts": True,
        "download_id":"123"  # 可选：指定固定 UUID 字符串；不指定则自动生成
        # 可选："headers": {"User-Agent": "..."}, "proxy": "http://127.0.0.1:7890",
        # 可选直播："live_seconds": 60, "live_limit": 100, "live_poll_interval": 5,
    }

    did = start_download(json.dumps(sample_cfg, ensure_ascii=False))


    time.sleep(10)
    print(f"[mgr] request stop id={did}")
    mgr.stop(did, merge_mp4=True)

    while True:
        st = mgr.get_status(did)
        #print(f"[mgr] id={did} status={st}")
        if st == "done":
            #print(f"[mgr] id={did} result={mgr.result(did)}")
            break
        time.sleep(2)
        
    mgr.shutdown()